package com.warrior.superdata.dds.datasource;

import com.google.common.collect.Maps;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 动态数据源操作类
 */
@Slf4j
public class DDSHolder {

    /**
     * 连接对象Map
     */
    private Map<String, DDSTimer> ddsMap = Maps.newHashMap();

    private DDSHolder() {

    }

    /**
     * 单例构造器
     */
    private static class DDSHolderBuilder {
        private static DDSHolder instance = new DDSHolder();
    }

    /**
     * 创建单例对象
     *
     * @return
     */
    public static DDSHolder instance() {
        return DDSHolderBuilder.instance;
    }

    /**
     * 添加数据源
     * @param projectCode
     * @param dds
     */
    public synchronized void addDDS(String projectCode, HikariDataSource dds) {
        DDSTimer ddst = new DDSTimer(dds);
        ddsMap.put(projectCode, ddst);
    }

    /**
     * 获取数据源
     * @param projectCode
     * @return
     */
    public synchronized HikariDataSource getDDS(String projectCode){
        DDSTimer result = Optional.ofNullable(ddsMap.get(projectCode)).orElse(null);
        if(Objects.nonNull(result)){
            result.refreshTime();
            return result.getDataSource();
        }
        return null;
    }

    /**
     * 检查并释放过期的数据库连接
     */
    public synchronized void checkIdelDataSource(){
        if(ddsMap.size() != 0){
            Iterator<Map.Entry<String, DDSTimer>> it = ddsMap.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<String, DDSTimer> entry = it.next();
                if(entry.getValue().checkAndClose()){
                    it.remove();
                }
            }
        }
    }
}
